<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Common\Server;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Contract\TranslatorInterface;
use App\Common\Demand\Server\Jwt as JwtInterfaces;
use App\Common\Exception\Store\JwtCheckError;
use Firebase\JWT\JWT as JwtExt;
use Firebase\JWT\Key;
class Jwt implements JwtInterfaces
{
    #[Inject]
    protected  TranslatorInterface $translatorInterface;
    private $key = 'longxiao-jwtkey';
    //创建token
    public function createToken(array $tokenData):string{
      
        $payload = [
            'iss' => 'http://base.lxkj828.com',
            'aud' => 'http://base.lxkj828.com',
            'iat' => time(),
            'nbf' => time(),
            'exp'=> time()+7200,
            'data'=> $tokenData,
        ];
        $jwt = JwtExt::encode($payload, $this->key, 'HS384');
        return $jwt;
    }
    //检查token
    public function checkToken(string $token):array{
        try {
            JwtExt::$leeway = 60;//当前时间减去60，把时间留点余地
            $jwtContent = JwtExt::decode($token, new Key($this->key, 'HS384') ); //同上的方式，这里要和签发的时候对应
            $jwtArray = (array)$jwtContent;
            return $jwtArray['data'];
        } catch(\Firebase\JWT\SignatureInvalidException $e) { //签名不正确
            throw new JwtCheckError($this->translatorInterface->trans('admin.signError'));
        }catch(\Firebase\JWT\BeforeValidException $e) { // 签名在某个时间点之后才能用
            throw new JwtCheckError($this->translatorInterface->trans('admin.notStart'));
        }catch(\Firebase\JWT\ExpiredException $e) { // token过期
            throw new JwtCheckError($this->translatorInterface->trans('admin.expire'));
        }
    }
    public function refreshToken(string $token):string {
        $tokenData=$this->checkToken($token);
        return $this->createToken($tokenData);
    }
}